package com.hongkuncheng.cms.controller.admin;

import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import org.hibernate.Criteria;
import org.hibernate.criterion.*;
import org.hibernate.sql.JoinType;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.stereotype.Controller;
import com.hongkuncheng.cms.controller.BaseController;
import com.hongkuncheng.cms.helper.DataHelper;
import com.hongkuncheng.cms.helper.FileHelper;
import com.hongkuncheng.cms.helper.HttpHelper;
import com.hongkuncheng.cms.helper.StringHelper;
import com.hongkuncheng.cms.model.Admin;
import com.hongkuncheng.cms.model.Article;
import com.hongkuncheng.cms.model.ArticleReColumns;
import com.hongkuncheng.cms.model.Columns;
import com.hongkuncheng.cms.model.ColumnsReDepartment;
import com.hongkuncheng.cms.model.Dataitem;
import com.hongkuncheng.cms.model.DataitemReColumns;
import com.hongkuncheng.cms.model.DataitemReDepartment;
import com.hongkuncheng.cms.model.Department;
import com.hongkuncheng.cms.model.Zhuanti;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 静态生成
 *
 * @author 洪坤成
 */
@Controller
@Transactional
@RequestMapping("admin/createpage")
public class AcreatepageController extends BaseController {

    // 生成全部
    @RequestMapping
    public String index() {
        checkAdminPermission("office_create_all");
        List<String> filepaths = new ArrayList<String>();
        List<String> pageurls = new ArrayList<String>();
        // 主页
        filepaths.add("index.html");
        pageurls.add("/frontpage/homepage");
        // 所有栏目
        List<Columns> columnses = factorySession.createCriteria(Columns.class)
                .add(Restrictions.lt("columnsType.id", 6)).list();
        List<String> articleIds = new ArrayList<String>();
        for (Columns columns : columnses) {
            int pagecount = getPageCount(columns);
            for (int i = 1; i <= pagecount; i++) {
                boolean isfirst = true;
                Columns parent = null;
                if (columns.getParentId() != 0) {
                    parent = factorySession.get(Columns.class, columns.getParentId());
                    isfirst = parent.getColumnsType().getId() > 3;
                }
                String filepathDirectory = null;
                if (columns.getParentId() == 0 || isfirst) {
                    filepathDirectory = columns.getUrldirectory();
                    filepaths.add(filepathDirectory + "/" + (i < 2 ? "index" : i) + ".html");
                } else {
                    if (parent == null)
                        parent = factorySession.get(Columns.class, columns.getParentId());
                    if (parent.getColumnsType().getId() < 4) {
                        filepathDirectory = parent.getUrldirectory() + "/" + columns.getUrldirectory();
                        filepaths.add(filepathDirectory + "/" + (i < 2 ? "index" : i) + ".html");
                    } else {
                        filepathDirectory = columns.getUrldirectory();
                        filepaths.add(filepathDirectory + "/" + (i < 2 ? "index" : i) + ".html");
                    }
                }
                String pageurl = "/frontpage/columns?columnsid=" + columns.getId();
                if (pagecount > 0) pageurl += "&pageindex=" + i;
                pageurls.add(pageurl);
                // 部门分组
                for (ColumnsReDepartment crd : columns.getColumnsReDepartments()) {
                    Department department = crd.getDepartment();
                    pagecount = getPageCount(columns, department);
                    for (int j = 1; j <= pagecount; j++) {
                        filepaths.add(filepathDirectory + "/departments/" + department.getUrldirectory() + "/" +
                                (j < 2 ? "index" : j) + ".html");
                        pageurl = "/frontpage/columns?columnsid=" + columns.getId() + "&departmentid=" + department.getId();
                        if (pagecount > 0) pageurl += "&pageindex=" + j;
                        pageurls.add(pageurl);
                    }
                }
                // 对应相关详细文档
                for (ArticleReColumns arc : columns.getArticleReColumnses()) {
                    if (!articleIds.contains(columns.getId() + "-" + arc.getArticle().getId())) {
                        if (columns.getParentId() == 0) {
                            filepaths.add(columns.getUrldirectory() + "/detail/" + arc.getArticle().getId() + ".html");
                        } else {
                            if (parent == null)
                                parent = factorySession.get(Columns.class, columns.getParentId());
                            if (parent.getColumnsType().getId() < 4)
                                filepaths.add(parent.getUrldirectory() + "/" + columns.getUrldirectory() + "/detail/" +
                                        arc.getArticle().getId() + ".html");
                            else
                                filepaths.add(columns.getUrldirectory() + "/detail/" + arc.getArticle().getId() + ".html");
                        }
                        pageurls.add("/frontpage/columns?columnsid=" + columns.getId() + "&articleid=" +
                                arc.getArticle().getId());
                        articleIds.add(columns.getId() + "-" + arc.getArticle().getId());
                    }
                }
            }
        }
        articleIds.clear();
        // 所有专题
        List<Zhuanti> zhuantis = factorySession.createCriteria(Zhuanti.class).list();
        for (Zhuanti zhuanti : zhuantis) {
            filepaths.add(zhuanti.getUrldirectory() + "/index.html");
            pageurls.add("/frontpage/zhuanti?zhuantiid=" + zhuanti.getId());
            // 其对应专题栏目
            for (Columns columns : zhuanti.getColumnses()) {
                if (columns.getColumnsType().getId() == 6) {
                    int pagecount = getPageCount(columns);
                    for (int i = 1; i <= pagecount; i++) {
                        filepaths.add(zhuanti.getUrldirectory() + "/" + columns.getUrldirectory() + "/" +
                                (i < 2 ? "index" : i) + ".html");
                        String pageurl = "/frontpage/columns?columnsid=" + columns.getId();
                        if (pagecount > 0) pageurl += "&pageindex=" + i;
                        pageurls.add(pageurl);
                        // 对应相关详细文档
                        for (ArticleReColumns arc : columns.getArticleReColumnses()) {
                            if (!articleIds.contains(zhuanti.getId() + "-" + columns.getId() + "-"
                                    + arc.getArticle().getId())) {
                                filepaths.add(zhuanti.getUrldirectory() + "/" + columns.getUrldirectory() + "/detail/"
                                        + arc.getArticle().getId() + ".html");
                                pageurls.add("/frontpage/columns?columnsid=" + columns.getId() + "&articleid="
                                        + arc.getArticle().getId());
                                articleIds.add(zhuanti.getId() + "-" + columns.getId() + "-" + arc.getArticle().getId());
                            }
                        }
                    }
                }
            }
        }
        // 部门网站
        List<Department> departments = factorySession.createCriteria(Department.class)
                .add(Restrictions.isNotNull("urldirectory"))
                .add(Restrictions.isNotNull("datamodel"))
                .add(Restrictions.isNotNull("template"))
                .addOrder(Order.asc("sort")).list();
        for (Department department : departments) {
            filepaths.add("/departments/" + department.getUrldirectory() + ".html");
            pageurls.add("/frontpage/department?departmentid=" + department.getId());
        }
        // 其它列表
        List<Columns> othercolumnses = factorySession.createCriteria(Columns.class)
                .add(Restrictions.eq("columnsType.id", 3)).list();
        for (Columns columns : othercolumnses) {
            if (columns.getParentId() == 0) {
                filepaths.add(columns.getUrldirectory() + "/" + "index.html");
            } else {
                Columns parent = factorySession.get(Columns.class, columns.getParentId());
                if (parent.getColumnsType().getId() < 4)
                    filepaths.add(parent.getUrldirectory() + "/" + columns.getUrldirectory() + "/" + "index.html");
                else
                    filepaths.add(columns.getUrldirectory() + "/" + "index.html");
            }
            pageurls.add("/frontpage/other?otherid=" + columns.getId());
        }
        // 大众留言
        filepaths.add("leavemessage/index.html");
        pageurls.add("/frontpage/leavemessage");
        request.setAttribute("filepaths", filepaths);
        request.setAttribute("pageurls", pageurls);
        return "forward:progress";
    }

    // 生成主页
    @RequestMapping("homepage")
    public Object homepage() {
        checkAdminPermission("office_create_index");
        List<String> filepaths = new ArrayList<String>();
        List<String> pageurls = new ArrayList<String>();
        filepaths.add("index.html");
        pageurls.add("/frontpage/homepage");
        request.setAttribute("filepaths", filepaths);
        request.setAttribute("pageurls", pageurls);
        return "forward:progress";
    }

    // 栏目列表
    @RequestMapping("columns")
    public String columns() {
        // 一级菜单
        List<Columns> columns1es = new ArrayList<Columns>();
        List<Columns> columns1esTemp = factorySession.createCriteria(Columns.class)
                .add(Restrictions.lt("columnsType.id", 6))
                .add(Restrictions.eq("parentId", 0))
                .addOrder(Order.asc("sort")).list();
        // 二级菜单
        Map<String, List<Columns>> columns2Maps = new HashMap<String, List<Columns>>();
        for (Columns columns1 : columns1esTemp) {
            List<Columns> columns2Temps = factorySession.createCriteria(Columns.class)
                    .add(Restrictions.eq("columnsType.id", 1))
                    .add(Restrictions.eq("parentId", columns1.getId()))
                    .addOrder(Order.asc("sort")).list();
            if (columns1.getColumnsType().getId() == 1 || columns2Temps.size() > 0)
                columns1es.add(columns1);
            if (columns2Temps.size() > 0)
                columns2Maps.put(String.valueOf(columns1.getId()), columns2Temps);
        }
        request.setAttribute("columns1es", columns1es);
        request.setAttribute("columns2Maps", columns2Maps);
        return view();
    }

    // 获取栏目列表需要生成的静态页面
    @RequestMapping("columnsfilepaths")
    public String columnsfilepaths() {
        checkAdminPermission("office_create_columns");
        List<String> filepaths = new ArrayList<String>();
        List<String> pageurls = new ArrayList<String>();
        String[] columnsIds = request.getParameter("columnsids").split(",");
        boolean createarticleauto = Boolean.parseBoolean(request.getParameter("createarticleauto"));
        List<Columns> columnses = factorySession.createCriteria(Columns.class)
                .add(Restrictions.in("id", DataHelper.convertToIntegerArray(columnsIds)))
                .list();
        List<String> articleIds = new ArrayList<String>();
        for (Columns columns : columnses) {
            int pagecount = getPageCount(columns);
            for (int i = 1; i <= pagecount; i++) {
                boolean isfirst = true;
                Columns parent = null;
                if (columns.getParentId() != 0) {
                    parent = factorySession.get(Columns.class, columns.getParentId());
                    isfirst = parent.getColumnsType().getId() > 3;
                }
                String filepathDirectory = null;
                if (columns.getParentId() == 0 || isfirst) {
                    filepathDirectory = columns.getUrldirectory();
                    filepaths.add(filepathDirectory + "/" + (i < 2 ? "index" : i) + ".html");
                } else {
                    if (parent == null)
                        parent = factorySession.get(Columns.class, columns.getParentId());
                    if (parent.getColumnsType().getId() < 4) {
                        filepathDirectory = parent.getUrldirectory() + "/" + columns.getUrldirectory();
                        filepaths.add(filepathDirectory + "/" + (i < 2 ? "index" : i) + ".html");
                    } else {
                        filepathDirectory = columns.getUrldirectory();
                        filepaths.add(filepathDirectory + "/" + (i < 2 ? "index" : i) + ".html");
                    }
                }
                String pageurl = "/frontpage/columns?columnsid=" + columns.getId();
                if (pagecount > 0) pageurl += "&pageindex=" + i;
                pageurls.add(pageurl);
                // 部门分组
                for (ColumnsReDepartment crd : columns.getColumnsReDepartments()) {
                    Department department = crd.getDepartment();
                    pagecount = getPageCount(columns, department);
                    for (int j = 1; j <= pagecount; j++) {
                        filepaths.add(filepathDirectory + "/departments/" + department.getUrldirectory() + "/"
                                + (j < 2 ? "index" : j) + ".html");
                        pageurl = "/frontpage/columns?columnsid=" + columns.getId() + "&departmentid=" + department.getId();
                        if (pagecount > 0) pageurl += "&pageindex=" + j;
                        pageurls.add(pageurl);
                    }
                }
                if (createarticleauto) {
                    // 对应相关详细文档
                    for (ArticleReColumns arc : columns.getArticleReColumnses()) {
                        if (!articleIds.contains(columns.getId() + "-" + arc.getArticle().getId())) {
                            if (columns.getParentId() == 0) {
                                filepaths.add(columns.getUrldirectory() + "/detail/" + arc.getArticle().getId() + ".html");
                            } else {
                                if (parent == null)
                                    parent = factorySession.get(Columns.class, columns.getParentId());
                                if (parent.getColumnsType().getId() < 4)
                                    filepaths.add(parent.getUrldirectory() + "/" + columns.getUrldirectory() + "/detail/"
                                            + arc.getArticle().getId() + ".html");
                                else
                                    filepaths.add(columns.getUrldirectory() + "/detail/" + arc.getArticle().getId() + ".html");
                            }
                            pageurls.add("/frontpage/columns?columnsid=" + columns.getId() + "&articleid="
                                    + arc.getArticle().getId());
                            articleIds.add(columns.getId() + "-" + arc.getArticle().getId());
                        }
                    }
                }
            }
        }
        request.setAttribute("filepaths", filepaths);
        request.setAttribute("pageurls", pageurls);
        return "forward:progress";
    }

    // 专题频道
    @RequestMapping("zhuanti")
    public String zhuanti() {
        List<Zhuanti> zhuantis = factorySession.createCriteria(Zhuanti.class)
                .addOrder(Order.asc("sort")).list();
        request.setAttribute("zhuantis", zhuantis);
        return view();
    }

    // 获取专题频道需要生成的静态页面
    @RequestMapping("zhuantifilepaths")
    public String zhuantifilepaths() {
        checkAdminPermission("office_create_zhuanti");
        List<String> filepaths = new ArrayList<String>();
        List<String> pageurls = new ArrayList<String>();
        String[] zhuantiIds = request.getParameter("zhuantiids").split(",");
        boolean createcolumnsauto = Boolean.parseBoolean(request.getParameter("createcolumnsauto"));
        boolean createarticleauto = Boolean.parseBoolean(request.getParameter("createarticleauto"));
        List<Zhuanti> zhuantis = factorySession.createCriteria(Zhuanti.class)
                .add(Restrictions.in("id", DataHelper.convertToIntegerArray(zhuantiIds)))
                .list();
        List<String> articleIds = new ArrayList<String>();
        for (Zhuanti zhuanti : zhuantis) {
            filepaths.add(zhuanti.getUrldirectory() + "/index.html");
            pageurls.add("/frontpage/zhuanti?zhuantiid=" + zhuanti.getId());
            if (createcolumnsauto) {
                // 其对应专题栏目
                for (Columns columns : zhuanti.getColumnses()) {
                    if (columns.getColumnsType().getId() == 6) {
                        int pagecount = getPageCount(columns);
                        for (int i = 1; i <= pagecount; i++) {
                            filepaths.add(zhuanti.getUrldirectory() + "/" + columns.getUrldirectory() + "/"
                                    + (i < 2 ? "index" : i) + ".html");
                            String pageurl = "/frontpage/columns?columnsid=" + columns.getId();
                            if (pagecount > 0) pageurl += "&pageindex=" + i;
                            pageurls.add(pageurl);
                            if (createarticleauto) {
                                // 对应相关详细文档
                                for (ArticleReColumns arc : columns.getArticleReColumnses()) {
                                    if (!articleIds.contains(zhuanti.getId() + "-" + columns.getId() + "-"
                                            + arc.getArticle().getId())) {
                                        filepaths.add(zhuanti.getUrldirectory() + "/" + columns.getUrldirectory()
                                                + "/detail/" + arc.getArticle().getId() + ".html");
                                        pageurls.add("/frontpage/columns?columnsid=" + columns.getId() + "&articleid="
                                                + arc.getArticle().getId());
                                        articleIds.add(zhuanti.getId() + "-" + columns.getId() + "-"
                                                + arc.getArticle().getId());
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        request.setAttribute("filepaths", filepaths);
        request.setAttribute("pageurls", pageurls);
        return "forward:progress";
    }

    // 部门网站
    @RequestMapping("department")
    public String department() {
        List<Department> departments = factorySession.createCriteria(Department.class)
                .add(Restrictions.isNotNull("urldirectory"))
                .add(Restrictions.isNotNull("datamodel"))
                .add(Restrictions.isNotNull("template"))
                .addOrder(Order.asc("sort")).list();
        request.setAttribute("departments", departments);
        return view();
    }

    // 获取部门网站需要生成的静态页面
    @RequestMapping("departmentfilepaths")
    public String departmentfilepaths() {
        checkAdminPermission("office_create_department");
        List<String> filepaths = new ArrayList<String>();
        List<String> pageurls = new ArrayList<String>();
        String[] departmentIds = request.getParameter("departmentids").split(",");
        List<Department> departments = factorySession.createCriteria(Department.class)
                .add(Restrictions.in("id", DataHelper.convertToIntegerArray(departmentIds)))
                .list();
        for (Department department : departments) {
            filepaths.add("/departments/" + department.getUrldirectory() + ".html");
            pageurls.add("/frontpage/department?departmentid=" + department.getId());
        }
        request.setAttribute("filepaths", filepaths);
        request.setAttribute("pageurls", pageurls);
        return "forward:progress";
    }

    private Criteria getArticleCriteria(List<Criterion> criterions) {
        Criteria criteria = factorySession.createCriteria(Article.class, "this_")
                .createAlias("articleReColumnses", "arc", JoinType.LEFT_OUTER_JOIN)
                .createAlias("arc.columns", "article_columns", JoinType.LEFT_OUTER_JOIN)
                .createAlias("article_columns.zhuanti", "article_columns_zhuanti", JoinType.LEFT_OUTER_JOIN)
                .createAlias("admin", "article_admin", JoinType.LEFT_OUTER_JOIN)
                .createAlias("article_admin.department", "article_admin_department", JoinType.LEFT_OUTER_JOIN)
                .createAlias("article_admin.adminGlobalpermission",
                        "article_admin_adminGlobalpermission", JoinType.LEFT_OUTER_JOIN);
        for (Criterion criterion : criterions) criteria.add(criterion);
        return criteria;
    }

    // 文档列表
    @RequestMapping("article")
    public String article() {
        Admin admin = (Admin) request.getSession().getAttribute("admin");
        List<Criterion> criterions = new ArrayList<Criterion>();
        StringBuilder callbackparams = new StringBuilder();
        boolean onlyme = request.getParameter("onlyme") != null;
        request.setAttribute("onlyme", onlyme);
        if (onlyme || admin.getAdminGlobalpermission().getId() == 1) {
            criterions.add(Restrictions.eq("article_admin.id", admin.getId()));
            callbackparams.append("&onlyme=1");
        } else if (admin.getAdminGlobalpermission().getId() == 2) {
            criterions.add(Restrictions.eq("article_admin_department.id", admin.getDepartment().getId()));
        }
        int columnsId = request.getParameter("columnsid") == null ? -1 :
                Integer.parseInt(request.getParameter("columnsid"));
        int zhuantiId = request.getParameter("zhuantiid") == null ? -1 :
                Integer.parseInt(request.getParameter("zhuantiid"));
        if (columnsId > -1) {
            boolean onlycurcolumns = request.getParameter("onlycurcolumns") != null;
            if (onlycurcolumns) {
                criterions.add(Restrictions.eq("article_columns.id", columnsId));
                callbackparams.append("&onlycurcolumns=1");
            } else
                criterions.add(Restrictions.or(Restrictions.eq("article_columns.id", columnsId),
                        Restrictions.eq("article_columns.parentId", columnsId)));
            request.setAttribute("onlycurcolumns", onlycurcolumns);
            int childCount = Integer.parseInt(factorySession.createCriteria(Columns.class)
                    .add(Restrictions.eq("parentId", columnsId))
                    .setProjection(Projections.countDistinct("id"))
                    .uniqueResult().toString());
            request.setAttribute("onlycurcolumnsisshow", childCount > 0);
        } else if (zhuantiId > -1) {
            criterions.add(Restrictions.eq("article_columns_zhuanti.id", zhuantiId));
            callbackparams.append("&zhuantiid=" + zhuantiId);
        }
        request.setAttribute("columnsid", columnsId);
        request.setAttribute("zhuantiid", zhuantiId);
        String title = request.getParameter("title") == null ? "" : request.getParameter("title");
        if (!title.isEmpty()) {
            criterions.add(Restrictions.like("title", title, MatchMode.ANYWHERE));
            callbackparams.append("&title=" + title);
        }
        request.setAttribute("title", title);
        criterions.add(Restrictions.eq("articleState.id", 4));
        String sortfield = request.getParameter("sortfield") == null ? "id" : request.getParameter("sortfield");
        String sortmethod = request.getParameter("sortmethod") == null ? "desc" : request.getParameter("sortmethod");
        callbackparams.append("&sortfield=" + sortfield);
        callbackparams.append("&sortmethod=" + sortmethod);
        request.setAttribute("sortfield", sortfield);
        request.setAttribute("sortmethod", sortmethod);
        Criteria criterTemp = getArticleCriteria(criterions);
        if (callbackparams.length() > 0) callbackparams.deleteCharAt(0);
        request.setAttribute("callbackparams", callbackparams);
        int pageIndex = request.getParameter("pageindex") == null || request.getParameter("callbackparams") != null &&
                !callbackparams.toString().equals(request.getParameter("callbackparams")) ? 1 :
                Integer.parseInt(request.getParameter("pageindex"));
        int datasize = getDataSize();
        List<Integer> articleIds = criterTemp.setProjection(Projections.distinct(Projections.property("id")))
                .addOrder(sortmethod.equals("desc") ? Order.desc(sortfield) : Order.asc(sortfield))
                .setFirstResult((pageIndex - 1) * datasize).setMaxResults(datasize).list();
        System.out.println("articleIds:"+articleIds.size());
        Criteria criteriaArticle = factorySession.createCriteria(Article.class);
        List<Article> articles = new ArrayList<Article>();
        if (articleIds.size() > 0) articles = criteriaArticle.add(Restrictions.in("id", articleIds))
                .list();
        request.setAttribute("articles", articles);
        request.setAttribute("pageindex", pageIndex);
        int recordcount = 0;
        if (articleIds.size() > 0) {
            Criteria criterArticlePage = getArticleCriteria(criterions);
            recordcount = Integer.parseInt(criterArticlePage.setProjection(Projections.countDistinct("id"))
                    .uniqueResult().toString());
        }
        request.setAttribute("recordcount", recordcount);
        int pagecount = DataHelper.calcPageCount(recordcount, datasize);
        request.setAttribute("pagecount", pagecount);
        // 栏目集合
        List<Columns> columnses = new ArrayList<Columns>();
        List<Columns> columnsForZhuanties = new ArrayList<Columns>();
        List<Zhuanti> zhuantis = new ArrayList<Zhuanti>();
        List<Integer> zhuantiIds = new ArrayList<Integer>();
        List<Columns> columns1es = factorySession.createCriteria(Columns.class)
                .add(Restrictions.eq("parentId", 0)).addOrder(Order.asc("sort"))
                .list();
        for (Columns columns1 : columns1es) {
            List<Columns> columns2Temp = factorySession.createCriteria(Columns.class)
                    .add(Restrictions.eq("columnsType.id", 1))
                    .add(Restrictions.eq("parentId", columns1.getId()))
                    .addOrder(Order.asc("sort")).list();
            if (columns1.getColumnsType().getId() == 1 || columns2Temp.size() > 0)
                columnses.add(columns1);
            if (columns2Temp.size() > 0)
                for (Columns columns2 : columns2Temp) columnses.add(columns2);
            if (columns1.getColumnsType().getId() == 6) {
                if (!zhuantiIds.contains(columns1.getZhuanti().getId())) {
                    zhuantis.add(columns1.getZhuanti());
                    zhuantiIds.add(columns1.getZhuanti().getId());
                }
                columnsForZhuanties.add(columns1);
            }
        }
        request.setAttribute("columnses", columnses);
        request.setAttribute("zhuantis", zhuantis);
        request.setAttribute("columnsForZhuanties", columnsForZhuanties);
        return view();
    }

    // 获取文档列表需要生成的静态页面
    @RequestMapping("articlefilepaths")
    public String articlefilepaths() {
        checkAdminPermission("office_create_article");
        List<String> filepaths = new ArrayList<String>();
        List<String> pageurls = new ArrayList<String>();
        String[] articleIds = request.getParameter("articleids").split(",");
        List<Article> articles = factorySession.createCriteria(Article.class)
                .add(Restrictions.in("id", DataHelper.convertToIntegerArray(articleIds)))
                .list();
        for (Article article : articles) {
            for (ArticleReColumns arc : article.getArticleReColumnses()) {
                Columns columns = arc.getColumns();
                if (columns.getParentId() == 0) {
                    String filepath = columns.getUrldirectory() + "/detail/" + article.getId() + ".html";
                    if (columns.getColumnsType().getId() == 6) filepath = columns.getZhuanti().getUrldirectory() +
                            "/" + filepath;
                    filepaths.add(filepath);
                } else {
                    Columns parent = factorySession.get(Columns.class, columns.getParentId());
                    if (parent.getColumnsType().getId() < 4)
                        filepaths.add(parent.getUrldirectory() + "/" + columns.getUrldirectory() + "/detail/" +
                                article.getId() + ".html");
                    else
                        filepaths.add(columns.getUrldirectory() + "/detail/" + article.getId() + ".html");
                }
                pageurls.add("/frontpage/columns?columnsid=" + columns.getId() + "&articleid=" + article.getId());
            }
        }
        request.setAttribute("filepaths", filepaths);
        request.setAttribute("pageurls", pageurls);
        return "forward:progress";
    }

    // 生成文档+栏目+主页相关HTML
    @RequestMapping("articlerelevancefilepaths")
    public String articlerelevancefilepaths() {
        Admin admin = factorySession.get(Admin.class, ((Admin) request.getSession().getAttribute("admin")).getId());
        int departmentId = admin.getDepartment().getId(); // 当前用户所在部门ID
        List<String> filepaths = new ArrayList<String>();
        List<String> pageurls = new ArrayList<String>();
        String[] articleIds = request.getParameter("articleids").split(",");
        List<Article> articles = factorySession.createCriteria(Article.class)
                .add(Restrictions.in("id", DataHelper.convertToIntegerArray(articleIds)))
                .list();
        List<String> columnsIds = new ArrayList<String>();
        List<String> zhuantiIds = new ArrayList<String>();
        boolean homepage = false;
        for (Article article : articles) {
            for (ArticleReColumns arc : article.getArticleReColumnses()) {
                Columns columns = arc.getColumns();
                String filepath = null;
                Columns parent = null;
                if (columns.getZhuanti() == null) {
                    if (columns.getParentId() == 0) {
                        filepath = columns.getUrldirectory() + "/detail/" + article.getId() + ".html";
                        if (columns.getColumnsType().getId() == 6) filepath = columns.getZhuanti().getUrldirectory() +
                                "/" + filepath;
                    } else {
                        parent = factorySession.get(Columns.class, columns.getParentId());
                        if (parent.getColumnsType().getId() < 4)
                            filepath = parent.getUrldirectory() + "/" + columns.getUrldirectory() + "/detail/" +
                                    article.getId() + ".html";
                        else
                            filepath = columns.getUrldirectory() + "/detail/" + article.getId() + ".html";
                    }
                } else {
                    filepath = columns.getZhuanti().getUrldirectory() + "/" + columns.getUrldirectory() + "/detail/" +
                            article.getId() + ".html";
                }
                switch (article.getArticleState().getId()) {
                    case 1:
                        // 下架，删除静态HTML文件
                        FileHelper.delete(filepath);
                        break;
                    case 4:
                        // 发布
                        filepaths.add(filepath);
                        pageurls.add("/frontpage/columns?columnsid=" + columns.getId() + "&articleid=" + article.getId());
                        break;
                }
                if (!columnsIds.contains(article.getId() + "-" + columns.getId())) {
                    int pagecount = getPageCount(columns);
                    for (int i = 1; i <= pagecount; i++) {
                        String filepathDirectory = null;
                        if (columns.getZhuanti() == null) {
                            boolean isfirst = true;
                            if (columns.getParentId() != 0) {
                                if (parent == null) parent = factorySession.get(Columns.class, columns.getParentId());
                                isfirst = parent.getColumnsType().getId() > 3;
                            }
                            if (columns.getParentId() == 0 || isfirst) {
                                filepathDirectory = columns.getUrldirectory();
                                filepaths.add(filepathDirectory + "/" + (i < 2 ? "index" : i) + ".html");
                            } else {
                                if (parent == null)
                                    parent = factorySession.get(Columns.class, columns.getParentId());
                                if (parent.getColumnsType().getId() < 4) {
                                    filepathDirectory = parent.getUrldirectory() + "/" + columns.getUrldirectory();
                                    filepaths.add(filepathDirectory + "/" + (i < 2 ? "index" : i) + ".html");
                                } else {
                                    filepathDirectory = columns.getUrldirectory();
                                    filepaths.add(filepathDirectory + "/" + (i < 2 ? "index" : i) + ".html");
                                }
                            }
                        } else {
                            filepaths.add(columns.getZhuanti().getUrldirectory() + "/" + columns.getUrldirectory() +
                                    "/" + (i < 2 ? "index" : i) + ".html");
                        }
                        String pageurl = "/frontpage/columns?columnsid=" + columns.getId();
                        if (pagecount > 0) pageurl += "&pageindex=" + i;
                        pageurls.add(pageurl);
                        if (filepathDirectory != null) {
                            for (ColumnsReDepartment crd : columns.getColumnsReDepartments()) {
                                Department department = crd.getDepartment();
                                if (department.getId() == departmentId) {
                                    pagecount = getPageCount(columns, department);
                                    for (int j = 1; j <= pagecount; j++) {
                                        filepaths.add(filepathDirectory + "/departments/" + department.getUrldirectory() +
                                                "/" + (j < 2 ? "index" : j) + ".html");
                                        pageurl = "/frontpage/columns?columnsid=" + columns.getId() + "&departmentid=" +
                                                department.getId();
                                        if (pagecount > 0) pageurl += "&pageindex=" + j;
                                        pageurls.add(pageurl);
                                    }
                                }
                            }
                        }
                        if (columns.getZhuanti() != null && !zhuantiIds.contains(article.getId() + "-" + columns.getId() +
                                "-" + columns.getZhuanti().getId())) {
                            filepaths.add(columns.getZhuanti().getUrldirectory() + "/index.html");
                            pageurls.add("/frontpage/zhuanti?zhuantiid=" + columns.getZhuanti().getId());
                            zhuantiIds.add(article.getId() + "-" + columns.getId() + "-" + columns.getZhuanti().getId());
                        }
                    }
                    columnsIds.add(article.getId() + "-" + columns.getId());
                }
                if (parent != null && parent.getColumnsType().getId() == 1 && !columnsIds.contains(article.getId() + "-" +
                        parent.getId())) {
                    int pagecount = getPageCount(parent);
                    for (int i = 1; i <= pagecount; i++) {
                        String filepathDirectory = null;
                        if (parent.getZhuanti() == null) {
                            filepathDirectory = parent.getUrldirectory();
                            filepaths.add(filepathDirectory + "/" + (i < 2 ? "index" : i) + ".html");
                        } else {
                            filepaths.add(parent.getZhuanti().getUrldirectory() + "/" + parent.getUrldirectory() + "/" +
                                    (i < 2 ? "index" : i) + ".html");
                        }
                        String pageurl = "/frontpage/columns?columnsid=" + parent.getId();
                        if (pagecount > 0) pageurl += "&pageindex=" + i;
                        pageurls.add(pageurl);
                        if (filepathDirectory != null) {
                            for (ColumnsReDepartment crd : parent.getColumnsReDepartments()) {
                                Department department = crd.getDepartment();
                                if (department.getId() == departmentId) {
                                    pagecount = getPageCount(parent, department);
                                    for (int j = 1; j <= pagecount; j++) {
                                        filepaths.add(filepathDirectory + "/departments/" + department.getUrldirectory() +
                                                "/" + (j < 2 ? "index" : j) + ".html");
                                        pageurl = "/frontpage/columns?columnsid=" + parent.getId() + "&departmentid=" +
                                                department.getId();
                                        if (pagecount > 0) pageurl += "&pageindex=" + j;
                                        pageurls.add(pageurl);
                                    }
                                }
                            }
                        }
                        if (parent.getZhuanti() != null && !zhuantiIds.contains(article.getId() + "-" + parent.getId() +
                                "-" + parent.getZhuanti().getId())) {
                            filepaths.add(parent.getZhuanti().getUrldirectory() + "/index.html");
                            pageurls.add("/frontpage/zhuanti?zhuantiid=" + parent.getZhuanti().getId());
                            zhuantiIds.add(article.getId() + "-" + parent.getId() + "-" + parent.getZhuanti().getId());
                        }
                    }
                    columnsIds.add(article.getId() + "-" + parent.getId());
                }
                if (!homepage) {
                    for (DataitemReColumns drc : columns.getDataitemReColumnses()) {
                        if (drc.getDataitem().getDatamodel().getId() == 1 && !filepaths.contains("index.html")) {
                            filepaths.add("index.html");
                            pageurls.add("/frontpage/homepage");
                            homepage = true;
                            break;
                        }
                    }
                }
            }
        }
        request.setAttribute("filepaths", filepaths);
        request.setAttribute("pageurls", pageurls);
        return "forward:progress";
    }

    // 其它列表
    @RequestMapping("other")
    public String other() {
        List<Columns> columns1es = factorySession.createCriteria(Columns.class)
                .add(Restrictions.eq("columnsType.id", 3))
                .add(Restrictions.eq("parentId", 0))
                .addOrder(Order.asc("sort")).list();
        Map<String, List<Columns>> columns2Maps = new HashMap<String, List<Columns>>();
        for (Columns columns1 : columns1es) {
            List<Columns> columns2Temps = factorySession.createCriteria(Columns.class)
                    .add(Restrictions.eq("columnsType.id", 3))
                    .add(Restrictions.eq("parentId", columns1.getId()))
                    .addOrder(Order.asc("sort")).list();
            if (columns2Temps.size() > 0) columns2Maps.put(String.valueOf(columns1.getId()), columns2Temps);
        }
        request.setAttribute("columns1es", columns1es);
        request.setAttribute("columns2Maps", columns2Maps);
        return view();
    }

    // 获取其它列表需要生成的静态页面
    @RequestMapping("otherfilepaths")
    public String otherfilepaths() {
        checkAdminPermission("office_create_other");
        List<String> filepaths = new ArrayList<String>();
        List<String> pageurls = new ArrayList<String>();
        String[] othercolumnsIds = request.getParameter("otherids").split(",");
        boolean createarticleauto = Boolean.parseBoolean(request.getParameter("createarticleauto"));
        List<Columns> othercolumnses = factorySession.createCriteria(Columns.class)
                .add(Restrictions.in("id", DataHelper.convertToIntegerArray(othercolumnsIds)))
                .list();
        for (Columns columns : othercolumnses) {
            if (columns.getParentId() == 0) {
                filepaths.add(columns.getUrldirectory() + "/" + "index.html");
            } else {
                Columns parent = factorySession.get(Columns.class, columns.getParentId());
                if (parent.getColumnsType().getId() < 4)
                    filepaths.add(parent.getUrldirectory() + "/" + columns.getUrldirectory() + "/" + "index.html");
                else
                    filepaths.add(columns.getUrldirectory() + "/" + "index.html");
            }
            pageurls.add("/frontpage/other?otherid=" + columns.getId());
        }
        request.setAttribute("filepaths", filepaths);
        request.setAttribute("pageurls", pageurls);
        return "forward:progress";
    }

    // 大众留言
    @RequestMapping("leavemessage")
    public String leavemessage() {
        List<String> filepaths = new ArrayList<String>();
        List<String> pageurls = new ArrayList<String>();
        filepaths.add("leavemessage/index.html");
        pageurls.add("/frontpage/leavemessage");
        request.setAttribute("filepaths", filepaths);
        request.setAttribute("pageurls", pageurls);
        return "forward:progress";
    }

    // 生成静态页面
    @RequestMapping("progress")
    public String progress() {
        List<String> filepaths = (List<String>) request.getAttribute("filepaths");
        List<String> pageurls = (List<String>) request.getAttribute("pageurls");
        request.setAttribute("filepaths", StringHelper.join(filepaths.toArray(), ","));
        request.setAttribute("pageurls", StringHelper.join(pageurls.toArray(), ","));
        request.setAttribute("filecount", filepaths.size());
        return view();
    }

    // 生成静态页面（供Ajax调用）
    @RequestMapping("progressdo")
    @ResponseBody
    public void progressdo() {
        String filepath = applicationDirectory + "/" + request.getParameter("filepath");
        String pageurl = "http://localhost:" + serverPort + request.getParameter("pageurl");
        String filecontent = HttpHelper.get(pageurl);
        if (!FileHelper.Exists(filepath) || !filecontent.equals(FileHelper.Read(filepath)))
            FileHelper.write(filepath, filecontent);
    }

    // 获取页数
    private int getPageCount(Columns columns) {
        return getPageCount(columns, null);
    }

    // 获取页数
    private int getPageCount(Columns columns, Department department) {
        int pagecount = 1;
        if (columns.getColumnsType().getId() == 1 || columns.getColumnsType().getId() == 6) {
            for (Dataitem dataitem : columns.getDatamodel().getDataitems()) {
                if (dataitem.isPagesign()) {
                    Criteria criteriaArticle = factorySession.createCriteria(Article.class, "this_")
                            .createAlias("admin", "article_admin", JoinType.LEFT_OUTER_JOIN)
                            .createAlias("article_admin.department", "article_admin_department",
                                    JoinType.LEFT_OUTER_JOIN);
                    criteriaArticle.add(Restrictions.eq("articleState.id", 4));
                    if (department == null) {
                        // 部门筛选
                        List<Integer> departmentIds = new ArrayList<Integer>();
                        for (DataitemReDepartment drd : dataitem.getDataitemReDepartments())
                            departmentIds.add(drd.getDepartment().getId());
                        if (departmentIds.size() > 0) criteriaArticle
                                .add(Restrictions.in("article_admin_department.id", departmentIds));
                    } else {
                        // 部门分组
                        criteriaArticle.add(Restrictions.eq("article_admin_department.id", department.getId()));
                    }
                    List<Integer> articleIds = new ArrayList<Integer>();
                    articleIds.add(0);
                    if (dataitem.isDynamiccolumns()) {
                        // 动态栏目
                        for (ArticleReColumns arc : columns.getArticleReColumnses())
                            if (!articleIds.contains(arc.getArticle().getId()))
                                articleIds.add(arc.getArticle().getId());
                        List<Columns> childs = factorySession.createCriteria(Columns.class)
                                .add(Restrictions.eq("parentId", columns.getId())).list();
                        for (Columns child : childs) {
                            for (ArticleReColumns arc : child.getArticleReColumnses())
                                if (!articleIds.contains(arc.getArticle().getId()))
                                    articleIds.add(arc.getArticle().getId());
                        }
                    } else {
                        // 静态栏目
                        for (DataitemReColumns drc : dataitem.getDataitemReColumnses()) {
                            for (ArticleReColumns arc : drc.getColumns().getArticleReColumnses())
                                if (!articleIds.contains(arc.getArticle().getId()))
                                    articleIds.add(arc.getArticle().getId());
                            List<Columns> childs = factorySession.createCriteria(Columns.class)
                                    .add(Restrictions.eq("parentId", drc.getColumns().getId()))
                                    .list();
                            for (Columns child : childs) {
                                for (ArticleReColumns arc : child.getArticleReColumnses())
                                    if (!articleIds.contains(arc.getArticle().getId()))
                                        articleIds.add(arc.getArticle().getId());
                            }
                        }
                    }
                    criteriaArticle.add(Restrictions.in("id", articleIds));
                    if (dataitem.isHaveimage()) criteriaArticle.add(Restrictions.isNotNull("image"));
                    int recordcount = Integer.parseInt(criteriaArticle
                            .setProjection(Projections.countDistinct("id"))
                            .uniqueResult().toString());
                    pagecount = DataHelper.calcPageCount(recordcount, dataitem.getDatacount());
                    if (pagecount == 0) pagecount = 1;
                    else if (pagecount > 10) pagecount = 10;
                    break;
                }
            }
        } else {
            pagecount = 0;
        }
        return pagecount;
    }

}
